#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.basic.security.filter;


import ${package}.basic.component.RequestParameterWrapper;
import ${package}.common.utils.RsaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Description: 密码解密过滤器
 *
 * @author songcx
 * @date 2020/8/10 15:46
 *
 * <pre>
 *              ${copyright}
 *      Copyright (c) 2019. All Rights Reserved.
 * </pre>
 */
@Slf4j
public class RsaFilter extends OncePerRequestFilter {

	private static final String PASSWORD_PARAMETER = "password";

	/**
	 * Same contract as for {@code doFilter}, but guaranteed to be
	 * just invoked once per request within a single request thread.
	 * See {@link ${symbol_pound}shouldNotFilterAsyncDispatch()} for details.
	 * <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
	 * default ServletRequest and ServletResponse ones.
	 *
	 * @param request
	 * @param response
	 * @param filterChain
	 */
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

		RequestParameterWrapper wrapper = new RequestParameterWrapper(request, request.getParameterMap());
		String password = request.getParameter(PASSWORD_PARAMETER);
		if (StringUtils.isNotEmpty(password)) {
			try {
				password = RsaUtil.decrypt(password);
				// 重新设置密码
				wrapper.addParameter(PASSWORD_PARAMETER, password);
			} catch (Exception e) {
				log.info("解密失败：{}", e.getMessage());
			}
		}
		filterChain.doFilter(wrapper, response);
	}

}
